package server

import (
	"fmt"
	"wolongauth/database"
	"wolongauth/errhelp"

	"github.com/gofiber/fiber/v2"
)

func CommonAuthMiddleWare(c *fiber.Ctx) error {
	if c.Path() == "/login" || c.Path() == "/new" || IsPublic(c.Path()) {
		return c.Next()
	}
	s, err := SessionStore.Get(c)
	if !errhelp.ErrDoWithTag(err, "session get") {
		return c.JSON(fiber.Map{"code": 8000, "message": err.Error()})
	}
	user := s.Get("user")
	password := s.Get("password")
	if user == nil || password == nil {
		s.Set("msg", "请先登录！")
		s.Save()
		return c.Redirect("/login")
	}
	user_s := fmt.Sprintf("%s", user)
	password_s := fmt.Sprintf("%s", password)
	loginok, _ := database.Login(user_s, password_s)
	if !loginok {
		s.Set("msg", "身份有误，请重新登录！")
		s.Save()
		return c.Redirect("/login")
	}
	return c.Next()
}
